//
//  ZTTXVisualizedManager.m
//  APPDemo
//
//  Created by 郭红旗 on 2021/10/18.
//

#import "ZTTXVisualizedManager.h"
#import <UIKit/UIKit.h>
#import "UIView+AutoTrack.h"
#import "UIViewController+ZTTXHook.h"

@implementation ZTTXVisualizedManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static ZTTXVisualizedManager *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[ZTTXVisualizedManager alloc] init];
//        manager.modules = [SAThreadSafeDictionary dictionary];
    });
    return manager;
}

- (nullable NSDictionary *)propertiesWithView:(UIView *)view{
    if (![view isKindOfClass:UIView.class]) {
        return nil;
    }
    UIViewController *viewController = view.sensorsdata_viewController;
    if (!viewController) {
        return nil;
    }
    NSString *elementSelector = [ZTTXVisualizedManager viewPathForView:view atViewController:viewController];
    return @{@"$viewPath":elementSelector};
}

+ (NSString *)viewPathForView:(UIView *)view atViewController:(UIViewController *)viewController {
    
    NSArray *viewPaths = [[[self viewPathsForView:view] reverseObjectEnumerator] allObjects];
    NSString *viewPath = [viewPaths componentsJoinedByString:@"/"];

    return viewPath;
}

+ (NSArray<NSString *> *)viewPathsForView:(UIView<ZTTXAutoTrackViewPathProperty> *)view {
    NSMutableArray *viewPathArray = [NSMutableArray array];
    do { // 遍历 view 层级 路径
        if ([view conformsToProtocol:@protocol(ZTTXAutoTrackViewPathProperty)]) {
            [viewPathArray addObject:view.sensorsdata_heatMapPath];
        }
    } while ((view = (id)view.nextResponder) && [view isKindOfClass:UIView.class] && ![view isKindOfClass:UIWindow.class]);

    if ([view isKindOfClass:UIViewController.class]) {
        // 遍历 controller 层 路径
        [viewPathArray addObjectsFromArray:[self viewPathsForViewController:(UIViewController *)view]];
    }
    return viewPathArray;
}

+ (NSArray<NSString *> *)viewPathsForViewController:(UIViewController *)viewController {
    NSMutableArray *viewPaths = [NSMutableArray array];
    do {
        if ([viewController conformsToProtocol:@protocol(ZTTXAutoTrackViewPathProperty)]) {
            [viewPaths addObject:viewController.sensorsdata_heatMapPath];
        }
        viewController = (UIViewController *)viewController.parentViewController;
    } while (viewController);

    return viewPaths;
}

@end
